package com.marakana.yamba3;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.marakana.yamba1.YambaApplication1;

public class UpdateService1 extends Service {

	private static final String TAG = "UpdateService1";

	static final int DELAY = 60000; // 1 munite
	private Updater updater;
	private boolean runFlag = false;
	private YambaApplication1 yamba;

	@Override
	public void onCreate() {
		super.onCreate();
		this.yamba = (YambaApplication1) getApplication();
		this.updater = new Updater();

		Log.d(TAG, "OnCreate");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.runFlag = false;
		this.updater.interrupt();
		this.updater = null;
		this.yamba.setServiceRunning(false);
		Log.d(TAG, "OnDestroy");
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		this.runFlag = true;
		this.updater.start();
		this.yamba.setServiceRunning(true);
		Log.d(TAG, "OnStarted");
		return START_STICKY;
	}

	private class Updater extends Thread {

		@Override
		public void run() {
			UpdateService1 updateService = UpdateService1.this;
			while (updateService.runFlag) {
				Log.d(TAG, "Updater running");
				try {
					updateService.yamba.fetchStatusUpdates();
					Log.d(TAG, "Update ran");
					Thread.sleep(DELAY);
				} catch (InterruptedException e) {
					updateService.runFlag = false;
				}
			}
		}

	}

}
